package com.ftg.learn.rbac.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ftg.learn.rbac.entity.User;
import com.ftg.learn.rbac.mapper.UserMapper;
import com.ftg.learn.rbac.service.IUserService;
import com.ftg.learn.util.ResEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author Guo
 * @date 2022/2/8
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements IUserService {

    @Autowired
    UserMapper userMapper;

    /**
     * httpsession : jsp session 个人私有缓存 (不要存敏感信息)
     * 登入功能
     * @param username  前台用户名
     * @param password  前台密码
     * @return
     */
    @Override
    public ResEntity logIn(String username, String password, HttpSession session) {
        ResEntity re = new ResEntity();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uaccount",username);
        queryWrapper.eq("upassword",password);
        User user = userMapper.selectOne(queryWrapper);
        if (Objects.isNull(user)){
            return re.Failure();
        }
        session.setAttribute("uaccount",user.getUaccount());
        session.setAttribute("uname",user.getUname());
        session.setAttribute("uid",user.getUid());
        return re.OK();
    }


    /**
     * 查某个人具有的角色
     * @param uid
     * @return
     */
    @Override
    public List<Map<String, Object>> showRoleForUserId(Long uid) {
        return userMapper.showRoleForUserId(uid);
    }


    /**
     * Transactional
     * 事务操作 表示当前对所有public修饰的 成功提交 失败回滚
     *
     * 对操作的用户删除角色及添加新角色
     * @param rid
     * @param uid
     * @return
     */
    @Transactional(rollbackFor = SQLException.class)
    @Override
    public boolean roleGroup(List<Long> rid,Long uid) {
        userMapper.delRoleForUserId(uid);
        for (Long l : rid) {
            userMapper.saveRoleForUserId(l,uid);
        }
        return true;
    }


}
